package com.sumansoul.photodemo;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.sumansoul.photodemo.ImageUtils.GlideUtils;
import com.sumansoul.photodemo.popwindow.CommonPopupWindow;
import com.sumansoul.photodemo.twoActivity.SystemVideoActivity;
import com.sumansoul.photodemo.twoActivity.VideoActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.rl_head)
    RelativeLayout rlHead;
    @BindView(R.id.iv_view1)
    ImageView ivView1;
    @BindView(R.id.iv_view2)
    ImageView ivView2;
    @BindView(R.id.content)
    LinearLayout content;
    @BindView(R.id.btn)
    Button btn;
    @BindView(R.id.btn2)
    Button btn2;
    //选择头像的框
    private CommonPopupWindow popupWindow;

    private int imageTag = 0;
    /**
     * 内容提供者和XML配置一样
     */
    String fileProvider = "com.sumansoul.photodemo.fileprovider";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        AppPermissionUtils.requestCommonPermissions(MainActivity.this, new CommonInterface.OnPermisssionFinish() {
            @Override
            public void onPermisssionFinish() {
                init();
            }
        }, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);

    }

    private void init() {
        /**
         * 头像正方形裁剪
         */
        ivHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageTag = 0;
                showAll();
            }
        });


        /**
         * 随意裁剪
         */
        ivView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageTag = 1;
                showAll();
            }
        });


        /**
         * 不裁剪
         */
        ivView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageTag = 2;
                showAll();
            }
        });


        //自定义支持拍照，拍视频
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, VideoActivity.class);
                startActivity(intent);
            }
        });

        /**
         * 系统相机
         */
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, SystemVideoActivity.class);
                startActivity(intent);
            }
        });
    }


    //全屏弹出
    public void showAll() {

        if (popupWindow != null && popupWindow.isShowing()) return;
        View upView = LayoutInflater.from(this).inflate(R.layout.pop_select_icon, null);
        //测量View的宽高
        CommonPopupWindow.measureWidthAndHeight(upView);
        popupWindow = new CommonPopupWindow.Builder(this)
                .setView(R.layout.pop_select_icon)
                .setWidthAndHeight(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                .setBackGroundLevel(0.5f)//取值范围0.0f-1.0f 值越小越暗
                .setAnimationStyle(R.style.AnimUp)
                .setViewOnclickListener(new CommonPopupWindow.ViewInterface() {
                    @Override
                    public void getChildView(View view, int layoutResId) {


                        view.findViewById(R.id.pop_top).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                setMobilePhones();//拍照
                                popupWindow.dismiss();
                            }
                        });
                        view.findViewById(R.id.pop_bottom).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                setLocalPhoto();//从手机相册选择
                                popupWindow.dismiss();
                            }
                        });
                        view.findViewById(R.id.pop_cancle).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                popupWindow.dismiss();
                            }
                        });
                    }
                })
                .create();
        popupWindow.showAtLocation(content, Gravity.BOTTOM, 0, 0);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (popupWindow != null) {
            popupWindow.dismiss();
            popupWindow = null;
        }

    }

    /**
     * 相册
     */
    private void setLocalPhoto() {
        Intent albumIntent = new Intent(Intent.ACTION_PICK, null);
        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(albumIntent, ALBUM);
    }

    private final int CAMERA = 10;
    private final int ALBUM = 20;
    private final int CUPREQUEST = 50;
    private String picPath;
    private File mOutImage;
    private Uri mImageUri;
    private Uri uritempFile;
    private static final String SD_PATH = "/sdcard/dskqxt/pic/";
    private static final String IN_PATH = "/dskqxt/pic/";

    private void setMobilePhones() {

        //获得项目缓存路径
        String sdPath = this.getExternalCacheDir().getPath();
        //根据时间随机生成图片名

        String photoName = DateTimeHelper.format(new Date(), "yyyyMMddhhmmss") + ".jpg";
        picPath = sdPath + "/" + photoName;
        mOutImage = new File(picPath);

        //如果是7.0以上 那么就把uir包装
        if (Build.VERSION.SDK_INT >= 24) {
            mImageUri = FileProvider.getUriForFile(this, fileProvider, mOutImage);
        } else {
            //否则就用老系统的默认模式
            mImageUri = Uri.fromFile(mOutImage);
        }
        //启动相机
        Intent intent = new Intent();
        //录像
        // intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);

        //拍照
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);


        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
        startActivityForResult(intent, CAMERA);


    }


    /**
     * 设置裁剪
     */
    private void setCropPhoto() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //如果是7.0剪裁图片 同理 需要把uri包装
            //通过FileProvider创建一个content类型的Uri
            Uri inputUri = FileProvider.getUriForFile(this,
                    fileProvider, mOutImage);
            startPhotoZoom(inputUri);//设置输入类型
        } else {
            Uri inputUri = Uri.fromFile(mOutImage);
            startPhotoZoom(inputUri);
        }
    }

    //裁剪
    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        //sdk>=24
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //去除默认的人脸识别，否则和剪裁匡重叠
            intent.putExtra("noFaceDetection", false);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        }
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 宽高的比例
        //华为特殊处理 不然会显示圆

        if (imageTag == 0 || imageTag == 1) {
            if (Build.MANUFACTURER.equals("HUAWEI")) {
                //9998
                intent.putExtra("aspectX", 9998);
                intent.putExtra("aspectY", 9999);
            } else {
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
            }
            // outputX outputY 是裁剪图片宽高
            intent.putExtra("outputX", CommonUtils.dip2px(100));
            intent.putExtra("outputY", CommonUtils.dip2px(100));
        }

        intent.putExtra("return-data", false);
        //miui系统 特殊处理 return-data的方式只适用于小图。
        if (Build.MANUFACTURER.contains("Xiaomi")) {
            //裁剪后的图片Uri路径，uritempFile为Uri类变量
            String photoName = DateTimeHelper.format(new Date(), "yyyyMMddhhmmss") + ".jpg";

            uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + photoName);

            intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        }
//        else {
//            intent.putExtra("return-data", true);
//        }
        //保存格式
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        startActivityForResult(intent, CUPREQUEST);
    }


    /**
     * 保存bitmap到本地
     *
     * @param context the context
     * @param mBitmap the m bitmap
     * @return string
     */
    public static String saveBitmap(Context context, Bitmap mBitmap) {
        String savePath;
        File filePic;


        try {

            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                savePath = SD_PATH;
            } else {
                savePath = context.getApplicationContext().getFilesDir()
                        .getAbsolutePath()
                        + IN_PATH;
            }

            filePic = new File(savePath + generateFileName() + ".jpg");
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(filePic);
            //质量压缩保存80%
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);

            fos.flush();
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }

        return filePic.getAbsolutePath();
    }


    /**
     * 随机生产文件名
     *
     * @return
     */
    private static String generateFileName() {
        SimpleDateFormat timeStampFormat = new SimpleDateFormat(
                "yyyy_MM_dd_HH_mm_ss");
        String filename = timeStampFormat.format(new Date());

        return filename;
    }


    /**
     * Activity 返回数据
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == CAMERA) {
            if (imageTag == 2) {
                //不裁剪
                if (picPath != null) {
                    //展示页面
                    showLayout(picPath);
                }

            } else {
                // 裁剪相机照片
                setCropPhoto();
            }


        } else if (requestCode == ALBUM) {
            //裁剪本地相册
            if (data != null && data.getData() != null) {
                Uri data1 = data.getData();
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
                    picPath = data1.toString();
                } else {
                    picPath = data1.getPath();
                }
                // Uri --> Path
                if (picPath.contains("content://")) {
                    picPath = CommonUtils.getFilePathFromContentUri(data1, this.getContentResolver());
                }
                mOutImage = new File(picPath);
                if (imageTag == 2) {
                    //不裁剪
                    //展示页面
                    showLayout(picPath);
                } else {
                    // 裁剪相机照片
                    setCropPhoto();
                }

            }

        } else if (requestCode == CUPREQUEST) {
            if (data == null) {
                return;
            }
            Bundle extras = data.getExtras();
            String filePath;
            if (Build.MANUFACTURER.contains("Xiaomi")) {
                if (uritempFile != null) {
                    filePath = uritempFile.getPath();
                } else {
                    filePath = "";
                }
            } else {
                if (extras != null) {
                    Bitmap photo = extras.getParcelable("data");
                    filePath = saveBitmap(this, photo);
                } else {
                    filePath = "";
                }
            }
            //展示页面
            showLayout(filePath);

        }


    }

    private void showLayout(String filePath) {

        if (!TextUtils.isEmpty(filePath)) {
            Bitmap bitmap = BitmapFactory.decodeFile(filePath);

            filePath = saveBitmap(this, bitmap);
            if (imageTag == 0) {
                GlideUtils.showImageViewToCircle(MainActivity.this, filePath, ivHead);

            } else if (imageTag == 1) {

                GlideUtils.loadImgNoCash(MainActivity.this, filePath, ivView1);

            } else if (imageTag == 2) {

                GlideUtils.loadImgNoCash(MainActivity.this, filePath, ivView2);

            }

        }

    }


}
